<template>
  <div class="table">
    <div class="flex">
      <div v-if="showSelectColumn&&showSelectedColumnsTitle" class="item">
        <span style="color: #999999; font-size: 14px">
          已选中:
          <span style="color: #008bcc">{{ selectionData.length }}</span>个
        </span>
      </div>
      <div class="item">
        <slot name="buttonSlot" />
      </div>
    </div>
    <div
      :class="showSelectColumn&&showSelectedColumnsTitle ? 'tableList-option' : 'tableList'"
      class="overHidden"
    >
      <!-- {{ tableColumnsData }} -->
      <el-table
        ref="table"
        v-loading="loading"
        element-loading-text="加载中"
        :data="tableData"
        border
        highlight-current-row
        stripe
        style="width: 100%"
        @sort-change="handleSortChange"
        @selection-change="handleSelectionChange"
        :row-style="{height:'45px'}"
        :row-key="getRowKeys"
        :expand-row-keys="expandRowKeys"
        @expand-change="handleExpandChange"
      >
        <el-table-column
          v-if="showSelectColumn"
          type="selection"
          align="center"
          :disabled="true"
          width="50"
          :selectable="selectable"
        />
        <el-table-column
          type="index"
          align="center"
          :index="
            (i) => {
              return i + 1;
            }
          "
          label="序号"
          width="70"
        />
        <!-- prop是对应列内容的字段名 width是对应列宽度 sortable是是否排序 label是对应列名称 -->
        <template v-for="(item, index) in tableColumnsData">
          <el-table-column
            v-if="item.header"
            :key="item.label"
            :prop="item.param"
            :width="item.width ? item.width : ''"
          >
            <template slot="header">
              <slot :name="item.header" />
              <div
                style="cursor: pointer; display: inline-block;"
                @click="handleTableColumnSetting()"
                title="自定义列"
                v-if="item.label=== tableColumnsData[tableColumnsData.length-1].label&&!tableOption.label"
              >
                <i :class="bHover?'el-icon-s-tools':'el-icon-setting'"></i>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            v-else-if="!item.slotName"
            :key="item.label"
            :prop="item.param"
            :width="item.width ? item.width : ''"
            :sortable="item.sortable ? true : false"
            :label="item.label"
            :type="item.type?item.type:''"
          >
            <template v-if="!item.notSearch" #header>
              <TypePopover
                ref="typepopover"
                v-if="tableUpStauts === 1"
                :column-index="index"
                :column="item"
                :filter-options="item.typeObj&&item.typeObj.list"
                :filter-name="item.typeObj&&item.typeObj.listName"
                :table-up-stauts="tableUpStauts"
                @tableUpdate="tableUpdate($event, item.label)"
              />
              <div
                style="cursor: pointer; display: inline-block;"
                title="自定义列"
                @click="handleTableColumnSetting()"
                v-if="item.label=== tableColumnsData[tableColumnsData.length-1].label&&!tableOption.label"
              >
                <i :class="bHover?'el-icon-s-tools':'el-icon-setting'"></i>
              </div>
              <!-- {{ item }} -->
            </template>
            <!-- 因为有些参数需要判定比如性别所以判断一下 -->
            <template slot-scope="scope">
              <span v-if="item.render">
                <div v-html="item.render(scope.row)" />
                <!-- {{ item.render(scope.row) }} -->
              </span>
              <span v-else-if="item.file">
                <el-link @click.native="handlePreviewPicture(scope.row,item)">查看</el-link>
              </span>
              <span v-else-if="item.tree">
                <el-link @click.native="handlePreviewTree(scope.row,item)">查看</el-link>
              </span>
              <span v-else>{{ scope.row[item.param] }}</span>
            </template>
          </el-table-column>

          <el-table-column
            v-else
            :key="item.label"
            :label="item.label"
            :type="item.type?item.type:''"
            :width="item.width ? item.width : ''"
            align="center"
          >
            <template v-if="!item.notSearch" #header>
              <TypePopover
                ref="typepopover"
                v-if="tableUpStauts === 1"
                :column-index="index"
                :column="item"
                :filter-options="item.typeObj&&item.typeObj.list"
                :filter-name="item.typeObj&&item.typeObj.listName"
                :table-up-stauts="tableUpStauts"
                @tableUpdate="tableUpdate($event, item.label)"
              />
              <div
                style="cursor: pointer; display: inline-block;"
                @click="handleTableColumnSetting()"
                title="自定义列"
                v-if="item.label=== tableColumnsData[tableColumnsData.length-1].label&&!tableOption.label"
              >
                <i :class="bHover?'el-icon-s-tools':'el-icon-setting'"></i>
              </div>
              <!-- {{ item }} -->
            </template>
            <template v-else #header>
              <div style="white-space: nowrap; ">
                {{ item.label }}
                <span
                  style="cursor: pointer;margin-left:5px"
                  @click="handleTableColumnSetting()"
                  title="自定义列"
                  v-if="item.label=== tableColumnsData[tableColumnsData.length-1].label&&!tableOption.label"
                >
                  <i :class="bHover?'el-icon-s-tools':'el-icon-setting'"></i>
                </span>
              </div>

              <!-- {{ item }} -->
            </template>
            <template #default="scope">
              <slot :name="item.slotName" :row="scope.row" />
            </template>
          </el-table-column>
        </template>
        <!-- 操作 -->
        <el-table-column
          v-if="tableOption.label"
          :width="tableOption.width ? tableOption.width : '200'"
          :label="tableOption.label"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template slot="header">
            <div
              style="cursor: pointer; display: inline-block;"
              @click="handleTableColumnSetting()"
              v-if="tableOption.label"
              title="自定义列"
            >
              {{ tableOption.label}}
              <i
                :class="bHover?'el-icon-s-tools':'el-icon-setting'"
              ></i>
            </div>
          </template>
          <template slot-scope="scope">
            <span
              v-for="(item, index) in tableOption.options"
              :key="index"
              style="white-space: nowrap;"
            >
              <!-- <el-button
                v-if="!item.slotName"
                style="margin-right:5px; color:#64D9D6"
                v-show="item.isShow ? item.isShow(scope.row) : true"
                :icon="item.icon"
                :type="item.type"
                plain
                :disabled="item.render ? item.render(scope.row) : false"
                @click="handleButton(item.methods, scope.row, scope.$index)"
              >{{ item.label }}</el-button>-->
              <span
                class="table-btns-box"
                :class="{'table-del-box':item.methods==='del'}"
                v-if="!item.slotName"
                style="margin-right:5px;"
                :disabled="item.render ? item.render(scope.row) : false"
                @click="handleButton(item.methods, scope.row, scope.$index)"
              >
                <i :class="item.icon"></i>
                <span>{{ item.label }}</span>
              </span>
              <span
                v-if="item.slotName"
                style="display: flex; align-items: center; justify-content: center;"
                v-show="item.isShow ? item.isShow(scope.row) : true"
                :key="index"
                :disabled="item.render ? item.render(scope.row) : false"
                @click="handleButton(item.methods, scope.row, scope.$index)"
              >
                <slot :name="item.slotName" :row="scope.row" />
              </span>
            </span>
          </template>
        </el-table-column>
        <!-- <el-table-column width="50">
          <template slot="header">
            <div style="cursor: pointer; display: inline-block;" @click="handleTableColumnSetting()">
              <i :class="bHover?'el-icon-s-tools':'el-icon-setting'"></i>
            </div>
          </template>
        </el-table-column>-->
      </el-table>
      <el-dialog :visible.sync="imgDialogVisible">
        <el-image
          class="el-upload-list__item-thumbnail"
          :src="`data:image/jpeg;base64,${imageUrl}`"
          alt
        />
      </el-dialog>
      <el-dialog
        :visible.sync="treeConfig.DialogVisible"
        :before-close="handleBeforeTreeDialogClose"
      >
        <el-tree
          ref="treedialog"
          :data="treeConfig.List"
          show-checkbox
          :props="treeConfig.Propstype"
          node-key="areaGroupId"
          accordion
          :highlight-current="true"
          :default-expanded-keys="treeConfig.CheckedList"
          :default-checked-keys="treeConfig.CheckedList"
        ></el-tree>
      </el-dialog>
      <tableColumnDialog
        ref="tableColumn"
        :tableColumnSum="tableColumnSum"
        :show="dialogTableColumnVisible"
        :tableColumns="tableColumnsData"
        :allTableColumns="allTableColumn"
        :loadSaveColumnWhenTableChange="loadSaveColumnWhenTableChange"
        @cancelColumn="cancelColumn"
      ></tableColumnDialog>
    </div>
    <!-- 表格结束 -->
    <!-- 翻页 -->
    <div class="pagination2">
      <Pagination
        :page-size="size"
        :current-page="page"
        :total-size="total"
        @changePageSize="handleSizeChange"
        @changeCurrentPage="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script>
import { Message } from "element-ui";
import Pagination from "@/components/Pagination";
import TypePopover from "./typePopover.vue";
import { mapGetters } from "vuex";
import tableColumnDialog from "@/components/tableColumn";
import { mymixin } from "@/utils/mixinForTableColume.js";
export default {
  mixins: [mymixin],
  components: { Pagination, tableColumnDialog, TypePopover },
  props: {
    showSelectColumn: {
      type: Boolean,
      default: true,
    },
    showSelectedColumnsTitle: {
      type: Boolean,
      default: false,
    },
    loading: {
      // 预加载
      type: Boolean,
      default: false,
    },
    tableData: {
      // 表格数据
      type: Array,
      default: () => {
        return [];
      },
    },
    tableColumns: {
      // 表头数据
      type: Array,
      default: () => {
        return [];
      },
    },
    rowKey: {
      //这里看这一行中需要根据哪个属性值是id
      type: String,
      default: "",
    },
    expandRowKeys: {
      // 扩展数据
      type: Array,
      default: () => {
        return [];
      },
    },
    tableColumnSum: {
      // 表头数据
      type: String,
      default: "",
    },
    loadSaveColumnWhenTableChange: {
      //切换表格时，是否重新获取表头数据
      type: Boolean,
      default: false,
    },
    tableOption: {
      // 表格操作
      type: Object,
      default: () => {
        return {};
      },
    },
    page: {
      // 当前页
      type: Number,
      default: () => {
        return 1;
      },
    },
    size: {
      // 当前页展示数
      type: Number,
      default: () => {
        return 10;
      },
    },
    total: {
      // 总数
      type: Number,
      default: () => {
        return 0;
      },
    },
  },
  data() {
    return {
      bHover: false,
      imgDialogVisible: false,
      imageUrl: "",
      treeConfig: {
        data: [],
        CheckedList: [],
        Propstype: {},
        NodeKey: "",
        DialogVisible: false,
      },
      selectionData: [],
      tableColumnsData: [],
      tableUpStauts: 1,
      getRowKeys: (row) => {
        // 获取当前行id
        return row[this.rowKey]; // 这里看这一行中需要根据哪个属性值是id
      },
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission",
    }),
  },
  mounted() {
    // console.log("table mounted", this.tableColumns);
    this.tableColumnsData = this.tableColumns;
    !this.loadSaveColumnWhenTableChange && this.loadSaveColumn();
  },
  watch: {
    total: {
      handler(v) {
        // 尾页删完自动跳转上一页
        let newPage = JSON.parse(JSON.stringify(this.page));
        if (v > 0 && this.tableData.length == 0) {
          this.$emit("pageChange", --newPage);
        }
      },
    },
    tableColumns: {
      handler(v) {
        this.allTableColumn = [];
        if (v.length > 0) {
          console.log("table tableColumns watch", v);
          this.allTableColumn = v;
        }
      },
      immediate: true,
    },
    tableColumnSum: {
      handler(v) {
        if (v) {
          console.log("table tableColumnSum watch");
          //表切换时，通过loadSaveColumnWhenTableChange判断，是否需要通过接口获取表头
          if (this.loadSaveColumnWhenTableChange) {
            this.loadSaveColumn();
          }
          this.$refs.typepopover &&
            this.$refs.typepopover.forEach((item) => {
              item.cleanSearchContentWhenTopItemTypeChange();
            });
        }
      },
      immediate: true,
    },
  },
  methods: {
    setCurrentRow() {
      this.$refs.table.setCurrentRow();
    },
    clearSelection() {
      this.$refs.table.clearSelection();
    },
    toggleRowSelection(row, select) {
      this.$refs.table.toggleRowSelection(row, select);
    },
    // 切换当前一页展示多少条
    handleSizeChange(val) {
      this.$emit("sizeChange", val);
    },
    // 翻页
    handleCurrentChange(val) {
      this.$emit("pageChange", val);
    },
    // 按钮点击事件
    // methods方法名 row当前点击列数据 index当前点击的index
    handleButton(methods, row, index) {
      this.$emit("clickButton", { methods: methods, row: row, index: index });
    },
    //表格列名修改
    handleTableColumnSetting() {
      this.dialogTableColumnVisible = true;
      this.$refs.tableColumn.loadSaveColumn();
    },
    // 点击排序
    handleSortChange(val) {
      this.$emit("sortChange", val);
    },
    // 选中
    handleSelectionChange(row) {
      this.selectionData = row || [];
      this.$emit("handleSelectionChange", row);
    },
    //行扩展
    handleExpandChange(row, expandedRows) {
      if (!row[this.rowKey]) {
        this.$refs.table.toggleRowExpansion(row, false);
        return;
      }
      this.$emit("handleExpandChange", row, expandedRows);
    },
    // 选中删除
    delData() {
      this.$emit("delSelectionData", this.selectionData);
    },
    handlePreviewPicture(row, item) {
      console.log("handlePreviewPicture", row, item);
      const url = row[item.param];
      if (!url || url === "") {
        Message.warning("图片不存在，请上传");
        return;
      }
      this.imageUrl = url;
      this.imgDialogVisible = true;
    },
    handlePreviewTree(row, item) {
      console.log("handlePreviewTree", row);
      if (row[item.param].toString() === "") {
        return;
      }
      this.treeConfig.List = row.options;
      this.treeConfig.CheckedList = row[item.param];
      this.treeConfig.Propstype = item.treePropstype;
      this.treeConfig.NodeKey = item.treeNodeKey;
      console.log("handlePreviewTree data", this.treeConfig.CheckedList);
      this.treeConfig.DialogVisible = true;
    },
    handleBeforeTreeDialogClose(done) {
      this.$refs["treedialog"].setCheckedNodes([]);
      console.log("handlePreviewTree clear node");
      done();
    },
    // table项是否可以被选中
    selectable(row) {
      let falg = true;
      if (!row[this.rowKey]) {
        falg = false;
      } else {
        falg = true;
      }
      // console.log(row, 'falg', this.rowKey, falg)
      return falg;
    },
    tableUpdatePlus(e, name) {
      console.log(this.searchObj, 'tableUpdatePlus');
      this.$emit("tableUpdatePlus", this.searchObj, e, name);
    },
  },
};
</script>

<style lang="scss" scoped>
.flex {
  display: flex;
  justify-content: flex-start;
  align-items: center;

  .item {
    padding: 0 10px;
  }
}

.table {
  height: 100%;
  padding: 0 10px 10px 10px;
  overflow: auto;
  .tableList {
    // height: calc(100% - 10px);
  }

  .tableList-option {
    height: calc(100% - 53px);
    min-height: calc(100% - 53px);
  }

  .overHidden {
    overflow: hidden;
    height: calc(100% - 50px);
    ::v-deep .el-table {
      height: calc(100% - 20px);
      margin-top: 0;
      .el-table__body-wrapper {
        height: calc(100% - 37px);
        overflow-y: auto;
        //background-color: #2e383e;
      }
    }
  }

  // ::v-deep .el-table th.is-leaf:nth-last-child(3) {
  //   border-right: none;
  // }
  // ::v-deep .el-table td:nth-last-child(2) {
  //   border-right: none;
  // }
}
</style>
